#include "StdThread.h"
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>



struct StdThread
{
    pthread_t threadID;
};

Thread *InitThread(void *(*funcPtr)(void *), void *arg)
{
    Thread *t = (Thread*)malloc(sizeof(Thread));
    if(t == NULL)
    {
        printf("thread malloc error!\n");
        return NULL;
    }
    
    pthread_create(&t->threadID,NULL,funcPtr,arg);
    return t;
}

void* ThreadJoin(Thread *t)
{
    void *value;
    pthread_join(t->threadID,&value);
    return value;
}

void ThreadDetach(Thread *t)
{
    pthread_detach(t->threadID);
}

void ThreadCancel(Thread *t)
{
    pthread_cancel(t->threadID);
}

unsigned long int GetThreadId(Thread *t)
{
    return t->threadID;
}

void ClearThread(void *t)
{
    if(t == NULL)
        return;
    free(t);
}

unsigned long int GetSelfThrdID()
{
    return pthread_self();
}


struct StdMutex
{
    pthread_mutex_t mutex;
};


Mutex *InitMutex()
{
    Mutex *m = (Mutex*)malloc(sizeof(Mutex));
    if(m == NULL)
        return NULL;
    
    pthread_mutex_init(&m->mutex,NULL);
    return m;
}

void MutexLock(Mutex *m)
{
    pthread_mutex_lock(&m->mutex);
}

void MutexUnlock(Mutex *m)
{
    pthread_mutex_unlock(&m->mutex);
}

void ClearMutex(Mutex *m)
{
    if(m == NULL)
        return;

    pthread_mutex_destroy(&m->mutex);
    free(m);
}

struct StdCond
{
    pthread_cond_t cond;
};

Cond *InitCond()
{
    Cond *c = (Cond*)malloc(sizeof(Cond));
    if(c == NULL)
        return NULL;

    pthread_cond_init(&c->cond,NULL);
    return c;
}

void CondWait(Cond *c,Mutex *m)
{
    pthread_cond_wait(&c->cond,&m->mutex);
}

void CondSignal(Cond *c)
{
    pthread_cond_signal(&c->cond);
}

void CondBroadcast(Cond *c)
{
    pthread_cond_broadcast(&c->cond);
}

void ClearCond(Cond *c)
{
    if(c == NULL)
        return;

    pthread_cond_destroy(&c->cond);
    free(c);
}
